<template>
  <div class="user-manage">
    <div class="user-search">
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="searchForm.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roles" clearable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="user-list">
      <el-table
        :data="userList"
        border
        style="width: 100%"
      >
        <el-table-column align="center" label="ID" width="100">
          <template slot-scope="scope">
            {{ scope.$index + 1 + (pagination.pageNumber - 1) * pagination.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="180">
          <template slot-scope="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱">
          <template slot-scope="scope">
            {{ scope.row.email }}
          </template>
        </el-table-column>
        <el-table-column label="角色">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.roles"
              :disabled="scope.row.disabled"
              @change="changeUserRole(scope.row._id, scope.row.roles)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="更新日期">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            {{ scope.row.updatedAt }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="scope.row.disabled = !scope.row.disabled">
              {{ scope.row.disabled ? '切换角色' : '取消设置' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        :current-page.sync="pagination.pageNumber"
        :page-size="pagination.pageSize"
        layout="total, prev, pager, next"
        :total="pagination.total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { changeRole, getUserList } from '@/api/user'
import { mapGetters, mapMutations } from 'vuex'
export default {
  data() {
    return {
      userList: [],
      loading: false,
      options: [
        {
          label: '编辑人员',
          value: 'editer'
        },
        {
          label: '管理人员',
          value: 'admin'
        }
      ],
      pagination: {
        pageNumber: 1,
        pageSize: 10,
        total: 0
      },
      searchForm: {
        username: '',
        email: '',
        roles: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['name'])
  },
  created() {
    this.getList()
  },
  methods: {
    ...mapMutations('user', ['SET_ROLES']),
    // 切换角色
    async changeUserRole(id, roles) {
      try {
        const response = await changeRole({ id, roles })
        this.$message.success('角色修改成功')
        this.getList()
        if (this.name === response.data.username) {
          this.SET_ROLES(response.roles)
          this.$router.push('/dashboard').catch(() => {})
        }
      } catch (error) {
        console.log(error)
        this.getList()
      }
    },
    // 获取用户列表
    async getList(searchForm = {}) {
      var { pageNumber, pageSize } = this.pagination
      try {
        this.loading = true
        const response = await getUserList({ pageNumber, pageSize, ...searchForm })
        const data = response.data
        data.forEach(item => {
          item.disabled = true
        })
        this.userList = data
        this.pagination = response.pagination
        this.loading = false
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    },
    // 搜索
    async onSearch() {
      var form = this.searchForm
      try {
        this.loading = true
        await this.getList(form)
        this.loading = false
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    },
    // 取消
    onCancel() {
      this.$refs.searchForm.resetFields()
    },
    // 选择页码
    handleCurrentChange(val) {
      this.pagination.pageNumber = val
      this.fetchData(this.searchForm)
    }
  }
}
</script>

<style lang="scss" scoped>
.user-manage {
  margin: 30px 20px;
  .user-search {
    margin: 20px 100px;
    .el-form {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .el-button {
      margin-left: 10px;
    }
  }
}
.block {
  margin-top: 20px;
  text-align: center;
}
</style>
